package com.wh1200.mybatis.xmlless.model.component

import com.wh1200.mybatis.xmlless.model.MethodInfo
import com.wh1200.mybatis.xmlless.model.SelectColumn

/**
 *
 * @author 吴昊
 * @date 2024/1/23 10:04
 * @since v4.0.0
 * @version 1.0
 */
class SelectDeclaration(
    private val distinct: Boolean,
    private val columns: List<SelectColumn>,
    private val from: FromDeclaration,
    private val where: WhereDeclaration,
    private val groupBy: String,
    private val order: String,
    private val having: String,
    private val limit: String,
) {

  fun toSql(methodInfo: MethodInfo): String {
    val builder = StringBuilder("SELECT")
    if (distinct) {
      builder.append(" DISTINCT")
    }
    builder.appendLine().append("  ")
    builder.append(columns.joinToString(",\n  ") { it.toSql() })
    builder.appendLine().append(from.toSql(methodInfo))
    if (methodInfo.joinAppend.isNotBlank()) {
      builder.appendLine().append("  ").append(methodInfo.joinAppend)
    }
    builder.appendLine().append(where.toSql())
    if (groupBy.isNotBlank()) {
      builder.appendLine().append(groupBy)
    }
    if (order.isNotBlank()) {
      builder.appendLine().append(order)
    }
    if (having.isNotBlank()) {
      builder.appendLine().append(having)
    }
    if (limit.isNotBlank()) {
      builder.appendLine().append(limit)
    }
    if (methodInfo.scriptAppend.isNotBlank()) {
      builder.appendLine().append(methodInfo.scriptAppend)
    }
    return builder.toString().trim()
  }

}
